package com.zerox.controller;

import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @auth 吴志勇
 * @date 2022/11/2 15:26
 */

@Controller
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    // 处理登录的请求
    @PostMapping("/login")
    public String doLogin(HttpSession session, Model model, String username, String password){

        SysUser sysUser = sysUserService.login(username, password);

        if (sysUser != null){
            session.setAttribute("loginUser",sysUser);
            // 重定向
            return "redirect:user/tolist";
        }

        model.addAttribute("errorMsg","用户名或密码错误");

        return "login";
    }

    // 局部异常处理
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(Model model,RuntimeException e){
        model.addAttribute("errorMsg",e.getMessage());
        return "error";
    }
}
